Python游戏编程(五)Tic Tac Toe | 您所在的位置:网站首页 › tik tak toe游戏规则 › Python游戏编程(五)Tic Tac Toe |
Tic Tac Toe就是我们熟悉的井字棋游戏。我们将通过这个游戏,设计出来第一个人工智能(artificial intelligence, AI)程序,它可以对玩家的落子智能地作出相应。当然井字棋游戏地AI并不复杂,只是简单地几行代码而已。 这个游戏的AI可以概括如下: 首先,判断是否有能够让计算机获胜的落子位置。如果是,在那里落子;否则,执行步骤2. 判断受否有能够让玩家失败的落子位置。如果是,在那里落子,以便堵住玩家;否则,执行步骤3. 判断是否还有角(格子1、3、7或者9)为空。如果有,在此处落子;如果没有角为空,那么执行步骤4. 判断是否中心(格子5)为空。如果有,在此处落子;否则,执行步骤5。 在任意一个边(格子2、3、6或者8)落子。没有其他步骤了,因为如果执行到第5步,边是仅剩的空地了。该算法在getComputerMove()函数以及getComputerMove()所调用的其他函数中实现。
这里我们用一个简单的数据表示游戏版,也就是一系列的文本。 (一)导入模块 #Tic-Tac-Toe import random (二)drawBoard(board): 我们将通过一个函数实现打印游戏棋盘。将board列表传递给drawBoard()函数,根据board列表中的元素进行打印。 #打印棋盘 def drawBoard(board): #This function prints out the board that it was passed. #"board" is a list of 10 strings representing the board (ignore index 0) print(board[7]+'|'+board[8]+'|'+board[9]) print('-+-+-') print(board[4]+'|'+board[5]+'|'+board[6]) print('-+-+-') print(board[1]+'|'+board[2]+'|'+board[3]) print('-+-+-')(三)inputPlayerLetter(): #让玩家来选择X或者是O def inputPlayerLetter(): #Let the player enter which letter they want to be. #Return a list with the player's letter as the first item and the computer's letter as the secend. letter = ' ' while not (letter == 'X' or letter == 'O'): print('Do you want to be X or O ?') letter = input().upper() #The first element in the list is the player 's letter; the secend is the computer's letter. if letter == 'X': return ['X', 'O'] else: return ['O', 'X'] (四)whoGoesFirst(): #决定谁先走 def whoGoesFirst(): #Randomly choose which player goes first. if random.randint(0, 2) == 0: return 'computer' else: return 'player' (五)makeMove(board, letter, move): #在游戏版上放置一个标记 def makeMove(board, letter, move): board[move] = letter 列表的引用 所谓列表引用,简单理解就是对于列表来说,赋值符号(=)不是代表复制,而是代表对列表的引用。 >>> x = [1, 2, 3, 4] >>> y = x >>> y.append(5) >>> y [1, 2, 3, 4, 5] >>> x [1, 2, 3, 4, 5] (六)isWinner(bo,le):#判断玩家是否获胜 def isWinner(bo,le): return ((bo[7] == le and bo[8] == le a |
CopyRight 2018-2019 实验室设备网 版权所有 |